package org.example.elm_springboot.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class CartService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String CART_PREFIX = "cart:";

    public void addItemToCart(String userId, String itemId, int quantity) {
        String cartKey = CART_PREFIX + userId;
        Map<String, Integer> cart = (Map<String, Integer>) redisTemplate.opsForValue().get(cartKey);
        if (cart == null) {
            cart = new HashMap<>();
        }
        cart.put(itemId, quantity);
        redisTemplate.opsForValue().set(cartKey, cart);
    }

    public Map<String, Integer> getCart(String userId) {
        String cartKey = CART_PREFIX + userId;
        return (Map<String, Integer>) redisTemplate.opsForValue().get(cartKey);
    }

    public void removeItemFromCart(String userId, String itemId) {
        String cartKey = CART_PREFIX + userId;
        Map<String, Integer> cart = (Map<String, Integer>) redisTemplate.opsForValue().get(cartKey);
        if (cart != null) {
            cart.remove(itemId);
            redisTemplate.opsForValue().set(cartKey, cart);
        }
    }
} 